package com.ymy.thinking.in.spring.dependency.injection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * {@link Autowired} {@link Resource} 基于方法的依赖注入
 *
 * @author Ringo
 * @date 2021/9/30 12:03
 */
public class AnnotationDependencyMethodInjectionDemo {

    private UserHolder userHolder;

    private UserHolder userHolder2;

    // =============================================================
    // @Autowired @Resource @Bean 都可以实现方法注入
    @Autowired
    public void init1(UserHolder userHolder) {
        this.userHolder = userHolder;
    }

    @Resource
    public void init2(UserHolder userHolder) {
        this.userHolder2 = userHolder;
    }


    @Bean
    public UserHolder userHolder(User user) {
        return new UserHolder(user);
    }

    // =============================================================

    @Bean
    public User user() {
        return new User("zsf", 18);
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(AnnotationDependencyMethodInjectionDemo.class);
        AnnotationDependencyMethodInjectionDemo demo =
                applicationContext.getBean(AnnotationDependencyMethodInjectionDemo.class);
        System.out.println(demo.userHolder);
        System.out.println(demo.userHolder2);
        System.out.println(demo.userHolder == demo.userHolder2);
    }
}
